<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;

$GLOBALS['MS_VER'] = 3.0;

$pluginList = Typecho_Plugin::export();
$GLOBALS['TPV_AKT'] = array_key_exists('TePostViews', $pluginList['activated']) ? 1 : 0;

Typecho_Plugin::factory('admin/write-post.php')->bottom = 'addButton';
Typecho_Plugin::factory('admin/write-page.php')->bottom = 'addButton';

function themeFields(\Typecho\Widget\Helper\Layout $layout) {
    $link = new \Typecho\Widget\Helper\Form\Element\Text(
        'link', 
        NULL, 
        NULL, 
        '原文链接', 
        '输入原文URL，会在文章底部增加“阅读原文”按钮'
    );
    $layout->addItem($link);
}

function themeConfig($form)
{
    /* 信息弹窗 */
    echo '<div id="ms-check-update" style="padding: 0.1rem 1rem; background: #eeeeee; border-radius: 5px; display: none">
        <h3>有新版本主题可用</h3>
        <p>当前版本：<span id="ms-ver"></span>，新版本：<span id="ms-new-ver"></span></p>
        <p>更新内容：<br><span id="ms-upd-dtl"></span></p>
        <p>下载地址：<a href="" id="ms-dwn-adr">点击下载</a></p>
    </div>';
    echo '<script>var MS_VER='.$GLOBALS['MS_VER'].'</script>';
    echo '<script src="'. Helper::options()->themeUrl .'/check-update.js"></script>';
    //未激活插件
    if (!$GLOBALS['TPV_AKT'])
        echo '<div style="background: #FBE3E4; color: #8A1F11; padding: 8px 10px; border-radius: 2px;">推荐安装插件TePostViews以获得更完整体验。</div>';
    /* 信息弹窗结束 */
    
    $modelBlock = new \Typecho\Widget\Helper\Form\Element\Checkbox(
        'modelBlock',
        [
            // 'ShowStickPost'      => _t('置顶文章'),
            'ShowRecentPost'     => _t('首页展示最新文章'),
            'ShowRecentComments' => _t('最近回复'),
            'ShowCategory'       => _t('分类列表'),
            'ShowArchive'        => _t('文章归档'),
            'ShowOther'          => _t('随机文章'),
            // 'ShowSocial'         => _t('显示社交平台信息')
        ],
        // ['ShowStickPost', 'ShowRecentPost', 'ShowRecentComments', 'ShowCategory', 'ShowArchive', 'ShowOther', 'ShowSocial'],
        ['ShowRecentPost', 'ShowRecentComments', 'ShowCategory', 'ShowArchive', 'ShowOther'],
        _t('功能选择')
    );

    $form->addInput($modelBlock->multiMode());
    
    $stickPostID = new \Typecho\Widget\Helper\Form\Element\Text(
        'stickPostID',
        null,
        null,
        _t('置顶文章'),
        _t('首页置顶展示特定文章<br>输入文章的cid，通过英语逗号分隔<br>推荐不超过3个以获得最佳展示效果<br>留空则不启用')
    );
    
    $form->addInput($stickPostID);
    
    $categoryslug = new \Typecho\Widget\Helper\Form\Element\Text(
        'categoryslug',
        null,
        null,
        _t('指定分类的最近发布'),
        _t('首页展示指定分类下最近发布的文章列表<br>输入分类的slug，通过英语逗号分隔<br>推荐输入3的倍数个分类<br>留空则不启用')
    );
    
    $form->addInput($categoryslug);
    
    $socialInfo = new \Typecho\Widget\Helper\Form\Element\Textarea(
        'socialInfo',
        null,
        null,
        _t('联系我'),
        _t('展示“联系我”板块<br>一行一个，格式 <b>社交平台名,链接,图标,用户名</b><br>如 微信,#,fab fa-weixin,stsiao<br>若没有链接，则输#<br>其他部分若不存在则直接留空即可<br>整体留空则不启用<br><br>详细说明，请参阅<a target="_blank" href="https://www.bwsl.wang/csother/140.html">帮助</a>')
    );
    
    $form->addInput($socialInfo);
    
    $randompostcount = new \Typecho\Widget\Helper\Form\Element\Text(
        'randompostcount',
        null,
        null,
        _t('随机文章数量'),
        _t('输入展示随机文章的数量<br>此处留空上方勾选则展示8条，上方不勾选则不启用')
    );
    
    $form->addInput($randompostcount);
    
    $showLink = new \Typecho\Widget\Helper\Form\Element\Textarea(
        'showLink',
        null,
        null,
        _t('友链'),
        _t('展示友链板块<br>一行一个，格式 <b>名称,带http/https开头的链接</b>，其中名称部分支持HTML语法引入图片等自定义内容<br>留空则不启用')
    );
    
    $form->addInput($showLink);
    
    $customFooter = new \Typecho\Widget\Helper\Form\Element\Textarea(
        'customFooter',
        null,
        null,
        _t('自定义页脚'),
        _t('使用HTML语法自定义页脚内容<br>如果你需要的话，也可以在这里加入js代码等各种可以出现在HTML页面中的东西<br>留空则不启用')
    );
    
    $form->addInput($customFooter);

}

/* 实在不知道Typecho怎么根据mid获取分类信息了… */
function metasInfo($value,$slug)
{
    $db   = Typecho_Db::get();
    $prow = $db->fetchRow($db->select($value)->from('table.metas')->where('slug= ?', $slug));
    $text = $prow[$value];

    return $text;
}

/* 随机文章 */
function outputRandomPosts($count) {
    if (empty($count))
        $count = 8;
    $archive = Typecho_Widget::widget('Widget_Archive');
    $db = Typecho_Db::get();
    $select = $db->select()->from('table.contents')
        ->where('table.contents.type = ?', 'post')
        ->where('table.contents.status = ?', 'publish')
        ->order('', 'RAND()')
        ->limit($count);
    $rows = $db->fetchAll($select);
    if ($GLOBALS['TPV_AKT']) {
        foreach ($rows as $row) {
            $row = $archive->filter($row);
            echo '<li ><a ' . $linkClass . 'href="' . $row['permalink'] . '" title="' . $row['title'] . '">' . $row['title'] . '</a><br>
            <span style="margin-right:1em"><i class="fa fa-eye"></i>&nbsp;'.$row['viewsNum'].'</span>
            <span><i class="fa fa-comment"></i>&nbsp;'.$row['commentsNum'].'</span></li>';
        }
    }
    else {
        foreach ($rows as $row) {
            $row = $archive->filter($row);
            echo '<span><a ' . 'href="' . $row['permalink'] . '" title="' . $row['title'] . '">' . $row['title'] . '</a><br>
            <span style="margin-right:1em"><i class="fas fa-calendar-alt"></i>&nbsp;'. date('Y-m-d', $row['modified']) . '</span>
            <span><i class="fa fa-comment"></i>&nbsp;'.$row['commentsNum'].'</span></span>';
        }
    }
}


/* 表情 */
/* 解析主函数 */
function parseEmote($content, $comments = 0) {
    $content = preg_replace_callback('/\:\:\(\s*(呵呵|哈哈|吐舌|太开心|笑眼|花心|小乖|乖|捂嘴笑|滑稽|你懂的|不高兴|怒|汗|黑线|泪|真棒|喷|惊哭|阴险|鄙视|酷|啊|狂汗|what|疑问|酸爽|呀咩爹|委屈|惊讶|睡觉|笑尿|挖鼻|吐|犀利|小红脸|懒得理|勉强|爱心|心碎|玫瑰|礼物|彩虹|太阳|星星月亮|钱币|茶杯|蛋糕|大拇指|胜利|haha|OK|沙发|手纸|香蕉|便便|药丸|红领巾|蜡烛|音乐|灯泡|开心|钱|咦|呼|冷|生气|弱|吐血)\s*\)/is',
            'parsePaopaoEmoteCallback', $content);
    $content = preg_replace_callback('/\:\@\(\s*(高兴|小怒|脸红|内伤|装大款|赞一个|害羞|汗|吐血倒地|深思|不高兴|无语|亲亲|口水|尴尬|中指|想一想|哭泣|便便|献花|皱眉|傻笑|狂汗|吐|喷水|看不见|鼓掌|阴暗|长草|献黄瓜|邪恶|期待|得意|吐舌|喷血|无所谓|观察|暗地观察|肿包|中枪|大囧|呲牙|抠鼻|不说话|咽气|欢呼|锁眉|蜡烛|坐等|击掌|惊喜|喜极而泣|抽烟|不出所料|愤怒|无奈|黑线|投降|看热闹|扇耳光|小眼睛|中刀)\s*\)/is',
            'parseAruEmoteCallback', $content);
    // 评论区内容删除p标签
    if ($comments) {
        $content = substr(substr($content, 3, strlen($content)), 0, strlen($content) - 4);
    }
    return $content;
}
    
/* 泡泡表情回调 */
function parsePaopaoEmoteCallback($match){
    return '<img class="emote" src="'. Helper::options()->themeUrl .'/owo/biaoqing/paopao/'. str_replace('%', '', urlencode($match[1])) . '_2x.png">';
}
    
/* 阿鲁表情回调 */
function parseAruEmoteCallback($match){
    return '<img class="emote" src="'. Helper::options()->themeUrl .'/owo/biaoqing/aru/'. str_replace('%', '', urlencode($match[1])) . '_2x.png">';
}

/* TOC解析 */

global $toc;        // TOC网页文本
global $curid;      // 标题ID
global $tocParent;  // 上一个标题等级, h2 h3 ...
global $tocClass;   // TOC样式等级

function parseTOC_callback($matchs){
    $GLOBALS['curid'] = $GLOBALS['curid'] + 1;
    $matchs[2] = preg_replace('/<a.*?>(.*?)<\/a>/', '$1', preg_replace('/<a.*?>(.*?)<\/a>/', '$1', $matchs[2]));  // 脱标题超链接，脱2次为了解决标题本身就是网址时失效的问题
    
    if ($GLOBALS['tocParent'] == 0) {   // 第一个标题等级，永远为父级标题
        $GLOBALS['toc'] .= '<li class="category-level-0 category-parent"><a href="#TOC-' . (string)$GLOBALS['curid'] . '">' . $matchs[2] . '</a></li>';
    }
    
    else if ($matchs[1] == $GLOBALS['tocParent']) { // 当前标题与前一个标题平级
        $GLOBALS['toc'] .= $GLOBALS['tocClass'] == 0 ? '<li class="category-level-0 category-parent"><a href="#TOC-' . (string)$GLOBALS['curid'] . '">' . $matchs[2] . '</a></li>' : '<li class="category-level-' . $GLOBALS['tocClass'] . ' category-child category-level-odd"><a href="#TOC-' . (string)$GLOBALS['curid'] . '">' . $matchs[2] . '</a></li>';
    }
    
    else if ($matchs[1] > $GLOBALS['tocParent']) {  // 当前标题是前一个标题的孩子
        $GLOBALS['tocClass'] = $GLOBALS['tocClass'] + 1;
        $GLOBALS['toc'] = substr($GLOBALS['toc'], 0, -5);
        $GLOBALS['toc'] .= '<ul class="widget-list"><li class="category-level-' . $GLOBALS['tocClass'] . ' category-child category-level-odd"><a href="#TOC-' . (string)$GLOBALS['curid'] . '">' . $matchs[2] . '</a></li>';
    }
    
    else if ($matchs[1] < $GLOBALS['tocParent']) {  // 当前标题是前一个标题的父亲
        $GLOBALS['tocClass'] = $GLOBALS['tocClass'] - 1;
        $GLOBALS['toc'] .=  $GLOBALS['tocClass'] <= 0 ? '</ul><li class="category-level-0 category-parent"><a href="#TOC-' . (string)$GLOBALS['curid'] . '">' . $matchs[2] . '</a></li>' : '</ul><li class="category-level-' . $GLOBALS['tocClass'] . ' category-child category-level-odd"><a href="#TOC-' . (string)$GLOBALS['curid'] . '">' . $matchs[2] . '</a></li>';
    }
    
    else {  // 其他，默认为与上一个标题同级别
        $GLOBALS['toc'] .= '<li><a href="#TOC-' . (string)$GLOBALS['curid'] . '" class="category-level-' . $GLOBALS['tocClass'] . ' category-parent">' . $matchs[2] . '</a></li>';
    }
    
    $GLOBALS['tocParent'] = $matchs[1]; // 前一个标题的等级，判断下一个标题父子关系
    
    return '<h' . $matchs[1] . ' id="TOC-' . (string)$GLOBALS['curid'] . '">' . $matchs[2] . '</h' . $matchs[1] . '>';
}

function parseTOC($content){
    global $toc;
    $GLOBALS['curid'] = 0;
    $GLOBALS['tocParent'] = 0;
    $GLOBALS['tocClass'] = 0;
    $new = preg_replace_callback('/<h([2-6]).*?>(.*?)<\/h.*?>/s', 'parseTOC_callback', $content);
    
    for ($i = $GLOBALS['tocClass']; $i > 0; $i--) {
        $toc .= '</ul></li>';
    }
    return array('content'=>$new, 'toc'=>$toc);
}
    
/* 编辑器表情按钮 */
/**
 * 编辑界面添加Button
 */
function addButton(){
    echo '<script src="'. Helper::options()->themeUrl .'/owo/owo_custom.js"></script>';
    echo '<script type="text/javascript" src="'. Helper::options()->themeUrl .'/editor01.js"></script>';
    echo '<link rel="stylesheet" href="'. Helper::options()->themeUrl .'/owo/owo.min.css" />';
    echo '<style>#custom-field textarea{width:100%}
    .OwO span{background:none!important;width:unset!important;height:unset!important}
    .OwO .OwO-logo{
        z-index: unset!important;
    }
    .comment-mail-me{
        display:inline;
        text-align:right;
        margin-right: 1.3em;
        z-index: 2;
    }  
    .OwO .OwO-body .OwO-items{
        -webkit-overflow-scrolling: touch;
        overflow-x: hidden;
    }
    .OwO .OwO-body .OwO-items-image .OwO-item{
        max-width:-moz-calc(20% - 10px);
        max-width:-webkit-calc(20% - 10px);
        max-width:calc(20% - 10px)
    }
    @media screen and (max-width:767px){	
        .comment-info-input{flex-direction:column;}
        .comment-info-input input{max-width:100%;margin-top:5px}
        #comments .comment-author .avatar{
            width: 2.5rem;
            height: 2.5rem;
        }
    }
    @media screen and (max-width:760px){
        .OwO .OwO-body .OwO-items-image .OwO-item{
            max-width:-moz-calc(25% - 10px);
            max-width:-webkit-calc(25% - 10px);
            max-width:calc(25% - 10px)
        }
    }</style>';
}